package tp.pr5.gui;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
import tp.pr5.PlaceInfo;

public class MapView extends JPanel {
	NavigationPanel navPan;
	ArrayList<PlaceCell> map;
	LogView log;
	int currentCell;	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public MapView(LogView log){
		this.setLayout(new GridLayout(11,11));
		this.setBorder(new TitledBorder("City Map"));		
		this.map = new ArrayList<PlaceCell>();
		this.currentCell = 60;	
		this.log = log;
		build();
		
		
		//setInitialPlaceActive();
	}
	
	private void build(){
		for(int i=0; i< 11; i++){
			for(int j=0;j<11;j++){
				final PlaceCell pc = new PlaceCell(j,i);
				
				pc.addActionListener(new ActionListener(){
	
					@Override
					public void actionPerformed(ActionEvent arg0) {
						if(pc.getPlace() != null && pc.isVisited()){
							log.refresh(pc.getPlace());					
						}
					}
					
				});
				
				this.add(pc);
				map.add(pc);	
			}
		}
		
	}
	/**
	 * Sets the initial place active
	 */
	private void setInitialPlaceActive(){
		PlaceCell initial = map.get(currentCell);		
		initial.setActive(true);
	}
	/**
	 * Sets the current cell inactive
	 */
	public void setCurrentCellActive(boolean toggle){
		PlaceCell current = map.get(currentCell);		
		current.setActive(toggle);
	}
	/**
	 * Returns the placecell with the given coordinates
	 * @param x
	 * @param y
	 * @return
	 */
	public PlaceCell getPlaceCell(int x, int y){
		for(int i = 0; i<11*11;i++){
			if(map.get(i).getXv() == x && map.get(i).getYv() == y) return map.get(i);
		}
		return null;
	}
	/**
	 * Returns the placecell with the given Place
	 * @param pl	 
	 * @return
	 */
	public PlaceCell getPlaceCell(PlaceInfo pl){
		for(int i = 0; i<11*11;i++){
			if(map.get(i).getPlace()!=null) {
				if(map.get(i).getPlace().equals(pl)) return map.get(i);			
			}
		}
		return null;
	}
	/**
	 * sets the correct aspect to each cell
	 */
	public void refreshCellsState(PlaceInfo currentPlace){
		for(int i = 0; i<11*11;i++){
			if(map.get(i).isVisited()) {				
				if(map.get(i).isActive()) map.get(i).setActive(false);
				else					  map.get(i).setGray();				
			}else{
				map.get(i).setText("");
				map.get(i).setBackground(null);
			}			
		}
		PlaceCell pc = this.getPlaceCell(currentPlace);
		pc.setActive(true);
		
		if(pc.isSpaceShip){
			//rbt.getMainWindow().gameWon();
			// TODO
		}
	}
	/**
	 * sets the current cell
	 * @param i
	 */
	public void setCurrentCell(int i){
		this.currentCell = i;
	}
	
	public void initialize(){		
		setInitialPlaceActive();
	}
}
